package chapter15.fibonacci;

import chapter15.generator.Generator;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : DuJiabao
 * @Date : 2021/3/4 14:22
 * @Project : thinking_in_java
 * @File : null.java
 * @Desc :
 */
public class Fabonacci implements Generator<Integer> {
  private int count = 0;
  private Map<Integer, Integer> record = new HashMap<>();

  public Fabonacci() {
    record.put(0, 1);
    record.put(1, 1);
  }

  @Override
  public Integer next() {
    return fib(count++);
  }

  private int fib(int n) {
    if (n < 2) return record.get(n);
    if (!record.containsKey(n)) record.put(n, fib(n - 1) + fib(n - 2));
    return record.get(n);
  }

  public static void main(String[] args) {
    Fabonacci fabonacci = new Fabonacci();
    for (int i = 0; i < 100; i++) {
      System.out.println(fabonacci.next());
    }
  }
}
